//index.js
//获取应用实例
import { config } from '../../utils/config.js';
import { CouponBoxModel } from '../../model/coupon-box.js';
import { showLoading,  hideLoading } from '../../components/mask.js'
const couponBoxModel = new CouponBoxModel();

Page({
  data: {
	unUsedText: '未使用',
	usedText: '已使用/过期',
	couponName: '霸王鸡盒',
	couponStatus: false,   // 默认是未使用
	mycouponList: [], // 优惠券列表
	// openId: 'oFjWNBTSUpeqXnAE',
	statusId: 1, // 1 未使用  2 已使用
	page: 1,
	rows: 20,
	totalPage: 0 // 默认总页数
  },
  
  onLoad: function() {
  },
  
  onShow: function() {
	  this._initData();
	  this._loadCouponMyCouponListKing();
  },
  
  // 查看优惠券详情
  jumpCouponDetail: function(e) {
	  if(this.data.statusId == 2) {
		  return;
	  }
	  let couponInstanceCode = e.currentTarget.dataset.code;
	  if (couponInstanceCode) {
		  jd.navigateTo({
		  		url: '/pages/coupon-detail/index?couponInstanceCode=' + couponInstanceCode
		  });
	  }
  },
  
  loadMoreCouponList: function() {
	  if(this.data.totalPage > this.data.page) {
		  this.setData({
			  page: this.data.totalPage
		  });
		  this._loadCouponMyCouponListKing();
	  }
  },
  
  switchCouponStatus: function() {
	  this._initData();
	  this._changeStatus();
	  this.setData({
		  couponStatus: !this.data.couponStatus,
		  statusId: this.data.statusId
	  });
	  this._loadCouponMyCouponListKing();
  },
  
  _loadCouponMyCouponListKing: function() {
	  showLoading();
	  let userOpenId = jd.getStorageSync('openId') || app.globalData.openId;
	  const myCouponListKing = couponBoxModel.getMyCouponListKing(userOpenId, this.data.statusId, this.data.page, this.data.rows);
	  myCouponListKing.then((res) => {
		  this.setData({
			  mycouponList: this.data.mycouponList.concat(res.items),
			  totalPage: res.data.totalPage
		  });
		  hideLoading();
	  });
  },
  // 初始化数据
  _initData: function() {
	  this.setData({
		  mycouponList: [],
		  page: 1,
		  totalPage: 0
	  });
  },
  // 切换使用状态
  _changeStatus: function() {
	  if(this.data.statusId == 1) {
		  this.setData({
			  statusId: 2
		  });
	  } else {
		  this.setData({
			  statusId: 1
		  });
	  }
  }
});